var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d');
    MAX_EDGE = Math.min(canvas.width, canvas.height);
    FONT_HEIGHT = MAX_EDGE/20,
    MARGIN = 10,
    NUMERAL_SPACING = 20,
    RADIUS = MAX_EDGE / 2 - MARGIN,
    HOUR_RADIUS = RADIUS - MAX_EDGE / 4,
    MINUTE_RADIUS = RADIUS - MAX_EDGE / 6,
    SECOND_RADIUS = RADIUS - MAX_EDGE / 8,
    HAND_RADIUS = RADIUS - NUMERAL_SPACING;

// fuctions

function drawCircle() {
    context.beginPath();
    context.arc(canvas.width/2, canvas.height/2,
            RADIUS, 0, Math.PI*2, true);
    context.stroke();
}

function drawNumerals() {
    var numerals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        angle = 0,
        numeralWidth = 0;

    numerals.forEach(function(numeral) {
        angle = Math.PI * (numeral - 3) / 6;
        numeralWidth = context.measureText(numeral).width;
        context.fillText(numeral, canvas.width/2 + Math.cos(angle)*HAND_RADIUS - numeralWidth/2,
            canvas.height/2 + Math.sin(angle)*HAND_RADIUS + FONT_HEIGHT/2);
    });
}

function drawCentre() {
    context.beginPath();
    context.arc(canvas.width/2, canvas.height/2, 5, 0, Math.PI*2, true);
    context.fill();
}

function drawHand(loc, radius) {
    var angle = Math.PI * 2 * loc / 60 - Math.PI / 2;

    context.moveTo(canvas.width/2, canvas.height/2);
    context.lineTo(canvas.width/2 + Math.cos(angle) * radius, 
            canvas.height/2 + Math.sin(angle) * radius);
    context.stroke();
}

function drawHands() {
    var date = new Date,
        hour = date.getHours();
    hour = hour > 12 ? hour - 12 : hour;
    drawHand(hour * 5 + (date.getMinutes()/60), HOUR_RADIUS);
    drawHand(date.getMinutes(), MINUTE_RADIUS);
    drawHand(date.getSeconds(), SECOND_RADIUS);
    //console.log(date);
}

function drawClock() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    drawCircle();
    drawCentre();
    drawNumerals();
    drawHands();
}

// --main

context.font = FONT_HEIGHT + 'px Arial';
loop = setInterval(drawClock, 1000);
